'use strict'
import axios from 'axios'
import { Loading, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const config = {
  baseURL: 'http://localhost:8090'
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
}

const _axios = axios.create(config)

_axios.interceptors.request.use(
  function (config) {
    // 判断是否有token 如果有 在请求头上加入token 一起传递到后端
    const token = store.getters.GET_TOKEN
    if (token) {
      config.headers.common.token = token
    }
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    return response
  },
  function (error) {
    // Do something with response error
    return Promise.reject(error)
  }
)
export const wyaxios = _axios
export const request = (url, method, params, callback) => {
  const loading = Loading.service({
    body: true,
    lock: true,
    text: '拼命加载中',
    background: 'rgba(255,255,255,0.8)'
  })
  const config = {
    method: method
  }
  if (method === 'get') {
    config.params = params
  } else {
    const formData = new FormData()
    for (const key in params) {
      formData.append(key, params[key])
    }
    config.data = formData
  }
  _axios.request(url, config).then(response => {
    if (response.data.code === 200) {
      callback(response.data)
      return
    }
    if (response.data.code === 401) {
      router.push('/login')
    }
    Message.error(response.data.message)
  }).catch(error => {
    Message.error(error)
  }).finally(() => {
    loading.close()
  })
}

export const get = (url, params, callback) => {
  request(url, 'get', params, response => {
    callback(response.obj)
  })
}
export const post = (url, params, callback) => {
  request(url, 'post', params, response => {
    if (response.code === 200 && response.message) {
      Message.success(response.message)
    }
    callback(response.obj)
  })
}
export const asyncRequest = async (url, method, params) => {
  if (method === 'get') {
    config.params = params
  } else {
    const formData = new FormData()
    for (const key in params) {
      formData.append(key, params[key])
    }
    config.data = formData
  }
  return await _axios.request(url, config)
}
